using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.Threading.Tasks;
using Ant.DbServiceInterface;
using AutoMapper;
using Ant.Dto.PersonnelDto;
using System;
using System.Net.Mail;
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Authorization;

namespace Ant.Service.PersonnelManagement.Conntroller
{
    [Route("ant/{controller}/{action}")]
    public class LoginController : Controller
    {
        private IPersonneDataService _dbService;
        private IConfiguration _configuration;
        private IMapper _mapper;

        public LoginController(IPersonneDataService dbService, IConfiguration configuration, IMapper mapper)
        {
            _dbService = dbService;
            _configuration = configuration;
            _mapper = mapper;
        }

        [HttpGet]
        [Authorize(Roles = "Admin")]
        public IActionResult Test(){
            var a = DateTime.Now;
            var b = new DateTime(1999,2,2,2,2,2);
            return Ok(a>b);
        }

        // [EnableCors]
        [HttpPost]
        public async Task<IActionResult> Index([FromBody] LoginDto loginDto)
        {

            if (!await _dbService.ExistUser(loginDto.Email, loginDto.Pwd)) return BadRequest("账号或密码错误");


            var userInfo = _mapper.Map<GetUserByEmailResDto>(await _dbService.GetUserByEmailAsync(loginDto.Email));

            var securityAlgorithms = SecurityAlgorithms.HmacSha256;

            var claims = new Claim[]{
                new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub,"test"),
                new Claim(ClaimTypes.Role,userInfo.UserRoleNavigation.RoleName)
            };
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
            var signingKey = new SymmetricSecurityKey(secretByte);
            var signingCredentials = new SigningCredentials(signingKey, securityAlgorithms);
            var token = new JwtSecurityToken(
                issuer: "localhost",
                audience: "localhost",
                claims: claims,
                notBefore: System.DateTime.UtcNow,
                expires: System.DateTime.UtcNow.AddDays(1),
                signingCredentials: signingCredentials
            );
            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
            // HttpContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
            // HttpContext.Response.Cookies.Append("token", tokenStr,new CookieOptions(){
            //     // Domain = ".*",
            //     Expires=DateTimeOffset.Now.AddDays(1)
            // });
            // HttpContext.Session.SetString("token",tokenStr);
            
                if(userInfo.UserStore==null){
                    userInfo.UserStore=-1;
                }
            // HttpContext.Response.Headers.Add("Content-Type","charset=utf-8");
            return Ok(
                new {
                    Token=tokenStr,
                    userID=userInfo.UserId,
                    userEmail = userInfo.UserEmail,
                    userStore=userInfo.UserStore,
                    userName=userInfo.UserName,
                    userRole=userInfo.UserRole
                }
            );
            // return Ok(tokenStr);
        }

        [HttpGet]
        public IActionResult GetVerify(string Email)
        {
            var r = new Random();
            var verifyCode = r.Next(10000, 99999);

            MailMessage mailMsg = new MailMessage();//实例化对象
            mailMsg.From = new MailAddress("2587001557@qq.com", "Ant官方");//源邮件地址和发件人
            mailMsg.To.Add(new MailAddress($"{Email}"));//收件人地址
            mailMsg.Subject = "Ant验证码";//发送邮件的标题
            StringBuilder sb = new StringBuilder();
            sb.Append($"验证码：{verifyCode}");
            mailMsg.Body = sb.ToString();//发送邮件的内容
            SmtpClient client = new SmtpClient();//格式：smtp.126.com  smtp.164.com
            client.Host = "smtp.qq.com";
            client.Port = 587;//端口
            client.EnableSsl = true; // 使用 SLL 加密
            client.Credentials = new NetworkCredential("2587001557@qq.com", "bvpvdzkqztxdebic"); // 用户名和测试密码

            try
            {
                client.Send(mailMsg);
            }
            catch (SmtpException ex)
            {
                Console.WriteLine($"发送失败{ex.Message}");
            }
            Console.WriteLine("邮件已发送，请注意查收！");

            
            HttpContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
            HttpContext.Response.Headers.Add("Access-Control-Allow-Method","*");
            return Ok(verifyCode);
        }
    }
}